import { getDeviceParameterDb } from './device-parameter-database';

/**
 * 动态表名映射工具类
 * 用于替代硬编码的表名映射，从数据库元数据动态生成映射关系
 */
class DynamicTableMapping {
  private mappingCache: Map<string, string> = new Map();
  private cacheExpiry: number = 0;
  private readonly CACHE_DURATION = 30 * 60 * 1000; // 30分钟缓存

  /**
   * 从数据库元数据构建动态表名映射
   */
  private buildMapping(): Map<string, string> {
    const db = getDeviceParameterDb();
    const mapping = new Map<string, string>();

    try {
      // 从parameter_table_metadata获取所有表的元数据
      const metadata = (db as any).db.prepare(`
        SELECT table_name, table_code, short_name 
        FROM parameter_table_metadata 
        ORDER BY table_name
      `).all();

      metadata.forEach((meta: any) => {
        const tableName = meta.table_name;
        
        // 生成所有可能的显示名称变体
        const variants = this.generateNameVariants(meta);
        
        variants.forEach(variant => {
          if (variant && variant.trim()) {
            mapping.set(variant, tableName);
          }
        });
      });

      console.log(`✅ 动态生成了 ${mapping.size} 个表名映射条目，覆盖 ${metadata.length} 个表`);
      
    } catch (error) {
      console.error('❌ 构建动态表名映射失败:', error);
    }

    return mapping;
  }

  /**
   * 为表生成所有可能的名称变体
   */
  private generateNameVariants(meta: any): string[] {
    const variants: string[] = [];
    
    // 基础变体
    if (meta.short_name) {
      variants.push(meta.short_name); // "表 C.2"
      variants.push(meta.short_name.replace(/\s+/g, '')); // "表C.2"
    }
    
    if (meta.table_code) {
      variants.push(meta.table_code); // "C.2"
      variants.push(`表 ${meta.table_code}`); // "表 C.2"
      variants.push(`表${meta.table_code}`); // "表C.2"
    }

    // 处理特殊情况：C.109-1 => C.109_1
    const normalizedCode = meta.table_code?.replace(/-/g, '_');
    if (normalizedCode && normalizedCode !== meta.table_code) {
      variants.push(normalizedCode);
      variants.push(`表 ${normalizedCode}`);
      variants.push(`表${normalizedCode}`);
    }

    // 去重并过滤空值
    return [...new Set(variants)].filter(v => v && v.trim());
  }

  /**
   * 获取表名映射
   */
  public getMapping(): Map<string, string> {
    const now = Date.now();
    
    // 检查缓存是否过期
    if (now > this.cacheExpiry || this.mappingCache.size === 0) {
      this.mappingCache = this.buildMapping();
      this.cacheExpiry = now + this.CACHE_DURATION;
    }
    
    return this.mappingCache;
  }

  /**
   * 将显示名称转换为实际表名
   */
  public mapDisplayNameToTableName(displayName: string): string {
    if (!displayName) return displayName;
    
    const mapping = this.getMapping();
    return mapping.get(displayName) || displayName;
  }

  /**
   * 批量转换显示名称到表名
   */
  public mapMultipleNames(names: Record<string, string>): Record<string, string> {
    const mapping = this.getMapping();
    const result: Record<string, string> = {};
    
    Object.entries(names).forEach(([key, displayName]) => {
      result[key] = mapping.get(displayName) || displayName;
    });
    
    return result;
  }

  /**
   * 清除缓存，强制重新构建映射
   */
  public clearCache(): void {
    this.mappingCache.clear();
    this.cacheExpiry = 0;
  }

  /**
   * 获取映射统计信息
   */
  public getMappingStats(): {
    totalMappings: number;
    uniqueTables: number;
    cacheExpiry: Date;
    sampleMappings: Array<{displayName: string; tableName: string}>;
  } {
    const mapping = this.getMapping();
    const uniqueTables = new Set(mapping.values()).size;
    
    // 获取前10个映射作为样例
    const sampleMappings = Array.from(mapping.entries())
      .slice(0, 10)
      .map(([displayName, tableName]) => ({ displayName, tableName }));
    
    return {
      totalMappings: mapping.size,
      uniqueTables,
      cacheExpiry: new Date(this.cacheExpiry),
      sampleMappings
    };
  }

  /**
   * 验证所有硬编码映射是否可以被动态映射替代
   */
  public validateHardcodedMappings(hardcodedMapping: Record<string, string>): {
    isValid: boolean;
    missingMappings: string[];
    conflictingMappings: Array<{key: string; hardcoded: string; dynamic: string}>;
  } {
    const dynamicMapping = this.getMapping();
    const missingMappings: string[] = [];
    const conflictingMappings: Array<{key: string; hardcoded: string; dynamic: string}> = [];
    
    Object.entries(hardcodedMapping).forEach(([key, hardcodedValue]) => {
      const dynamicValue = dynamicMapping.get(key);
      
      if (!dynamicValue) {
        missingMappings.push(key);
      } else if (dynamicValue !== hardcodedValue) {
        conflictingMappings.push({
          key,
          hardcoded: hardcodedValue,
          dynamic: dynamicValue
        });
      }
    });
    
    return {
      isValid: missingMappings.length === 0 && conflictingMappings.length === 0,
      missingMappings,
      conflictingMappings
    };
  }
}

// 单例实例
let mappingInstance: DynamicTableMapping | null = null;

/**
 * 获取动态表名映射实例
 */
export function getDynamicTableMapping(): DynamicTableMapping {
  if (!mappingInstance) {
    mappingInstance = new DynamicTableMapping();
  }
  return mappingInstance;
}

/**
 * 便捷函数：将显示名称转换为表名
 */
export function mapDisplayNameToTableName(displayName: string): string {
  return getDynamicTableMapping().mapDisplayNameToTableName(displayName);
}

/**
 * 便捷函数：批量转换名称
 */
export function mapMultipleDisplayNames(names: Record<string, string>): Record<string, string> {
  return getDynamicTableMapping().mapMultipleNames(names);
}